import ctypes
import subprocess

from PyQt5.QtCore import QTimer


class External():
    def __init__(self, mainWindow):
        self.mainWindow = mainWindow
        self.ui = self.mainWindow.ui.external


    def loadData(self):
        print('Hello World!')

    def load_program(self, exe_path, program_name):
        if hasattr(self,'external_process'):
            self.external_process.kill()
        self.external_process = subprocess.Popen([exe_path], creationflags=subprocess.CREATE_NEW_CONSOLE)
        self.program_name = program_name
        # 在窗口准备好之后嵌入外部exe
        self.timer = QTimer()
        self.timer.timeout.connect(self.embed_external_exe)
        self.timer.start(300)
        QTimer.singleShot(3000, self.timer.stop)
        # QTimer.singleShot(1000, self.embed_external_exe)

    def embed_external_exe(self):
        # 获取外部exe的窗口句柄
        # external_hwnd = ctypes.windll.user32.FindWindowW(None, 'P2202')
        external_hwnd = ctypes.windll.user32.FindWindowW(None, self.program_name)
        # external_hwnd = findWindowByWindowClass('UnrealWindow')
        if not external_hwnd:
            print("找不到外部窗口，请检查窗口标题是否正确")
            return

        # 将外部exe的窗口设为子窗口
        parent_hwnd = self.ui.program.winId().__int__()
        ctypes.windll.user32.SetParent(external_hwnd, parent_hwnd)

        # 设置外部窗口的样式和位置
        style = ctypes.windll.user32.GetWindowLongW(external_hwnd, -16)  # 获取窗口样式
        style &= ~0x00C00000  # 去除标题栏
        ctypes.windll.user32.SetWindowLongW(external_hwnd, -16, style)  # 设置窗口样式
        ctypes.windll.user32.SetWindowPos(external_hwnd, 0, 0, 0, 800, 600, 0x0040 | 0x0004)  # 设置窗口位置和大小